package main.javassist.create;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewConstructor;
import javassist.CtNewMethod;
import javassist.bytecode.AccessFlag;


public class MakeClass {
	public static void main(String[] args) throws Exception {
		//1. 创建类
		ClassPool pool = ClassPool.getDefault();
		CtClass ct = pool.makeClass("cn.tedu.hello.HelloWorld");
		
		//2. 添加属性
		CtField fId = new CtField(CtClass.intType, "id", ct);
		fId.setModifiers(AccessFlag.PUBLIC);
		ct.addField(fId);
		
		CtField fName = new CtField(pool.get(String.class.getName()), "name", ct);
		fName.setModifiers(AccessFlag.PRIVATE);
		ct.addField(fName);
		
		//3. 添加构造方法
		CtConstructor c = CtNewConstructor.make("public HelloWorld(){ System.out.println(\"我是默认构造方法\"); }", ct);
		ct.addConstructor(c);
		
		//添加有参构造方法
		CtConstructor pc = new CtConstructor(new CtClass[] { pool.get(String.class.getName()) }, ct);
		//&0=this；$1代表第一个参数，$2,$3...，下标是从1开始
		pc.setBody("{ $0.name = $1; }");			//this.name = name;
		ct.addConstructor(pc);
		
		//4. 添加业务方法
		CtMethod hiMethod = CtNewMethod.make("public void hi(String name){ System.out.println(name); }", ct);
		ct.addMethod(hiMethod);
		
		ct.writeFile("bin/");
		System.out.println("执行完成");
	}
}
